[JAVA] 익명 클래스

업데이트:



✅ 익명 클래스란?

익명 클래스이름을 갖지 않는 클래스이다. 클래스 선언과 오브젝트 생성이 결합된 형태로 만들어지며, 상속할 클래스나 구현할 인터페이스를 생성자 대신 사용해서 정해진 형태로 만들어 사용한다. 클래스를 재사용할 필요가 없고, 구현한 인터페이스 타입으로만 사용할 경우에 유용하다.

new 인터페이스이름() { 클래스 본문 };



이해를 위해 간단한 예시를 들어보면, 생명체라는 부모클래스를 상속받는 사람 클래스가 있다고 치자. 사람은 총 60억명 있고, 이들은 각각 직업에 따라 하는 일이 다르며, 공통적인 특징은 없다. 잠깐 프로그램에 단발성으로 등장해서 자신이 맡은 일을 하고 사라진다고 치자.



그러면 이런상황에서 우리가 60억명의 사람들을 클래스로 만들어 구현하는 것이 나을지, 아니면 하나의 클래스에서 코드로 일시적으로 정의하여 쓰고 버리는것이 나을지 선택하면 된다. 아마 60억개의 클래스를 만들 사람은 없을거다.



어차피 단발성으로 등장해서 사용하고 다시는 안 쓸 오브젝트들 인데 클래스로 만들어서 유지보수 하기에는 부담이 너무 크고 불필요하다.



이럴때 바로 우리는 익명 클래스를 사용하는 것이다!



✅ 익명 클래스 구현 ( 인터페이스 )

📌 인터페이스

public interface StatementStrategy {
	PreparedStatement makePreparedStatement(Connection c) throws SQLException;
}


📌 일반 클래스 ( 이 클래스를 익명 클래스로 전환 할꺼임 )

public class AddStatement implements StatementStrategy {
	User user;
	
	public AddStatement(User user) {
		this.user = user;
	}
	
	public PreparedStatement makePreparedStatement(Connection c) throws SQLException {

		PreparedStatement ps = c.prepareStatement("insert into users(id,name,password) values(?,?,?)");
		ps.setString(1, user.getId());
		ps.setString(2, user.getName());
		ps.setString(3, user.getPassword());

		return ps;
	}
}

새로운 사용자를 DB에 추가하는 코드이다. 위 코드는 프로젝트 내에서 UserDao라는 단하나의 클래스에서만 사용되고 다른 클래스에서는 전혀 사용되지 않는다. 또한 StatementStrategy 라는 인터페이스를 상속받아 makePreparedStatement를 구현하고 있다.




📌 익명 클래스의 구현

...(생략)

public class UserDao {
	...
	// 사용자 추가 메소드
	public void add(final User user) throws SQLException {

		// AddStatement를 익명 내부 클래스로 전환
		this.jdbcContext.workWithStatementStrategy(new StatementStrategy() {

			public PreparedStatement makePreparedStatement(Connection c) throws SQLException {
				PreparedStatement ps = c.prepareStatement("insert into users(id, name, password) values(?,?,?)");
				ps.setString(1, user.getId());
				ps.setString(2, user.getName());
				ps.setString(3, user.getPassword());
				return ps;
			}
		});
	}

	...
	

코드를 보면 this.jdbcContext.workWithStatementStrategy(new StatementStrategy() { AddStatement 클래스 본문 } 이런 형태로 만들어진것을 볼 수 있다. 우리가 구현 할 클래스를 따로 이름을 정해주지 않고 다른 클래스 내부에 직접 만들어 주는 형태다.

위 코드에서 익명 클래스는 new StatementStrategy() { ... } 이다. 익명클래스를 파라미터로 가진 형태이다.




댓글남기기